<template>
	<view class="content bg-img bg-mask " v-if="show22">
		<u-navbar :title=" i18n.peca.i14" background="rgba(0,0,0,0)" back-icon-color="#fff" title-color="#fff"></u-navbar>
		<!-- -->
		<view class="scroll">
			<view class="flex head  f30" style="display: none;">
				<text class="f-1 flex justify-center" @click="flg(1)" :class="[{ action: show }, { color: show }]">充币</text>
				<text class="f-1 flex justify-center" @click="flg(2)" :class="[{ action: show1 }, { color: show1 }]">提币</text>
				<text class="f-1 flex justify-center" @click="flg(3)" :class="[{ action: show2 }, { color: show2 }]">转账</text>
			</view>
			<view class="padding-lr rchg " v-if="show">
				<view class="response flex justify-end " @click="rchg">
					<view class="rchgRec">{{ i18n.tongdui.i1 }}</view>
				</view>
				<view class="qianbao flex justify-between">
					<view class="left response" style="width: calc(100%);">
						<view class="t1 ">{{ i18n.tongdui.i2 }}：</view>
						<view class="f26 t2 text-cut ">{{ dataInfo.config.peAddress }}</view>
					</view>
					<view class="right bg-gradual-green r " style="width: 120rpx; width: 120rpx; display: none;"></view>
				</view>

				<view class="curr" style="margin-top: 100rpx;">
					<text>{{ i18n.tongdui.i3 }}</text>
					<view class="inpt  flex block">
						<text class="text-cut" style="width: 78vw;font-size: 26rpx;">{{ addr }}</text>
						<!-- <input type="text" value="" v-model="openAddress"  disabled class="text-cut" style="width: 400rpx !important;" /> -->
						<text
							style=" background-color:#161919; flex-wrap: nowrap; white-space: nowrap;  display: flex; align-items: center;  justify-content: center;   padding: 5rpx  10rpx;  border-radius: 5rpx; text-align: center; "
							v-clipboard:copy="url"
							v-clipboard:success="copy"
							@click="dianji"
						>
							{{ i18n.tongdui.i11 }}
						</text>
						<!-- <image src="../../static/sanjiaox.png" mode="" style="width:36rpx ; height: 20rpx;"></image> -->
					</view>
				</view>

				<view class="curr" style="margin-top: 100rpx;">
					<view class=" flex justify-between">
						<text>{{ i18n.tongdui.i4 }}</text>
						<!-- <text>USDT : {{ usdtt ? usdtt : '0' }}</text> -->
					</view>
					<view class="inpt">
						<input type="number" value="" @input="enter" v-model="pe" :placeholder="i18n.tongdui.i5" />

						<text style="color: #999999;" class="f30 text-right" v-if="usdt">={{ pe * dataserial }}PEC</text>

						<!-- <image src="../../static/sanjiaox.png" mode="" style="width:36rpx ; height: 20rpx;"></image> -->
					</view>
				</view>
				<view class="text-center block margin-top-xl text-white flex flex-direction justify-center " v-if="jiaData == 1">
					<text>
						{{ i18n.index.index7 }}
						<text class="color">{{ redata.serial }}</text>
						{{ i18n.index.index8 }}
					</text>
					<text class="margin-top-sm">{{ i18n.index.index12 }} : {{ redata.peSurplus }}{{ i18n.index.index13 }}</text>
				</view>
				<text class="text-center block margin-top-xl text-white" v-else></text>
				<view class="flex flex-direction justify-center align-center" style="color: #04BD9E;">
					<text style="color: #FFFFFF;" class="margin-top-sm">PECA{{ i18n.peca.i13}}</text>
					<text class="margin-top-sm">{{ i18n.peca.i6}}≤{{ func() }}PECA</text>
					<text class="margin-top-sm" v-if="dataInfo.config.pec_serial == 1 && dataInfo.config.peca_surplus > 0">
						{{ dataInfo.config.pec_scale }}PEC : {{ dataInfo.config.peca_scale }}PECA
					</text>
					<text class="margin-top-sm" v-else>
						{{ dataInfo.config.pec_scale }}uPEC : {{ dataInfo.config.peca_scale }}uPECA
					</text>
				</view>
				<view class="btn margin-top-xl" @click="aacc" v-if="showBtn">{{ i18n.tongdui.i6 }}</view>

				<!-- <text
					class="flex  align-center  justify-center f28   block"
					style="color: #FFFFFF; margin:  0  auto; margin-top: 120rpx;  text-align: center;"
				>
					{{ i18n.tongdui.i9 }}
				</text> -->
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			pe: '',
			showInput: true,
			addr: '',
			show: true,
			show1: false,
			show2: false,
			CustomBar: this.CustomBar,
			list: [
				{
					name: '为本地址充币',
					disabled: false,
				},
				{
					name: '为其他地址充币',
					disabled: false,
				},
			],

			value: '为本地址充币',
			openAddress: '',
			counterAddr: '',
			uu: '',
			usdt: '',
			show22: true,
			url: '',
			addrr: '',
			surplus: '',
			redata: {},
			jiaData: true,
			usdtt: '',
			showBtn: true,
			dataserial: '',
			dataInfo: {},
			// info:uni.getStorageSync('data').data
		};
	},
	computed: {
		i18n() {
			return this.$t('message');
		},
	},
	onShow() {
		setTimeout(() => {
			this.initWebSocket();
		}, 500);
	},
	onBackPress() {
		uni.closeSocket();
		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
		});
		this.websock.close(); //离开路由之后断开websocket连接
	},
	onHide() {
		uni.closeSocket();
		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
		});
		this.websock.close(); //离开路由之后断开websocket连接
	},

	onLoad(e) {
		var obj = setInterval(() => {
			if (window.tronWeb) {
				clearInterval(obj);

				this.show22 = true;
				this.triggerSmartContract();
				this.payRatio();
				this.get();
			} else {
				this.show = false;
				this.show22 = false;
			}
		}, 20);

		this.surplus = uni.getStorageSync('surplus');
		this.jiaData = uni.getStorageSync('pay');

		this.openAddress = e.openAddress;
		this.uu = uni.getStorageSync('uu');

		this.addr = uni.getStorageSync('uid');
	},
	methods: {
		func() {
			var info = uni.getStorageSync('data');

			if (info?.group == 'B') {
				this.pee = this.dataInfo.config.pec_inside_excahnge;
				return this.dataInfo.config.pec_inside_excahnge;
			}
			if (info.fly == 1) {
				this.pee = this.dataInfo.config.pec_level[5];
				return this.dataInfo.config.pec_level[5];
			}
			if (info.level) {
				this.pee = this.dataInfo.config.pec_level[info.level];
				return this.dataInfo.config.pec_level[info.level];
			}
			this.pee = 0;
			return 0;
		},
		async get() {
			const res = await this.$u.post(
				'/index.php/api/pe/index',
				{},
				{
					token: uni.getStorageSync('token'),
				},
			);
			this.dataInfo = res.data;
		},
		async payRatio() {
			const res = await this.$u.post(
				'/index.php/api/pe/usdt_pe',
				{ serial: this.redata.serial },
				{
					token: uni.getStorageSync('token'),
				},
			);
			this.dataserial = res.data;
			console.log('res11111111111111111: ', res);
		},
		async triggerSmartContract() {
			const trc20ContractAddress = 'TDNTEhUvZ1jxq4wZBkGRoHHxX2972neevR'; //contract address
			var address = uni.getStorageSync('uid');

			try {
				let contract = await tronWeb.contract().at(trc20ContractAddress);

				let result = await contract.balanceOf(address).call();

				this.usdtt = parseInt(result._hex, 16) / 100000000;

				console.log('this.usdtt', this.usdtt);
			} catch (error) {
				console.error('trigger smart contract error', error);
			}
		},

		//--------------

		initWebSocket() {
			//初始化weosocket
			const wsuri = 'wss://preacher.ink:2501';
			this.websock = new WebSocket(wsuri);
			this.websock.onmessage = this.websocketonmessage;
			this.websock.onopen = this.websocketonopen;
			this.websock.onerror = this.websocketonerror;
			this.websock.onclose = this.websocketclose;
		},
		websocketonopen() {
			//连接建立之后执行send方法发送数据
			let actions = { test: '12345' };
			this.websocketsend(JSON.stringify(actions));
		},
		websocketonerror() {
			//连接建立失败重连
			//this.initWebSocket();
		},
		websocketonmessage(e) {
			//console.log('e :>> ', e);
			//数据接收
			this.redata = JSON.parse(e.data);
			// console.log('this.redata22222222222  :>> ', this.redata);
			this.$forceUpdate();
		},
		websocketsend(Data) {
			//数据发送
			this.websock.send(Data);
		},
		websocketclose(e) {
			//关闭
		},

		//--------------
		dianji() {
			uni.$showMsg(this.i18n.tongdui.i10);
			this.url = this.addr;
		},

		copy(e) {
			//alert(this.openAddress)
			uni.$showMsg(this.i18n.tongdui.i10);
			this.url = this.addr;
		},
		onError(e) {},
		enter(e) {
			this.usdt = (e.detail.value * this.uu).toFixed(2);
		},
		rchg() {
			uni.navigateTo({
				url: 'tongduii?addr=' + this.addr,
			});
		},
		ret() {
			uni.navigateBack({
				delta: 1,
			});
		},
		async getAddr() {
			let obj = {
				// uid: uni.getStorageSync("uid"),
			};

			const res = await this.$u.post('/index.php/api/pe/buyPe', obj, {
				token: uni.getStorageSync('token'),
			});

			this.addrr = res.data;
		},

		radioGroupChange(e) {
			e == '为本地址充币' ? (this.showInput = true) : (this.showInput = false);
		},

		async aacc() {
			console.log('this.pe :>> ', this.pe);
			console.log('this.pee :>> ', this.pee);
			if (Number(this.pe) == 0) {
				return uni.$showMsg(this.i18n.tongdui.i7);
			}

			if (Number(this.pe) <= Number(this.pee)) {
				this.pay();
			} else {
				uni.$showMsg(this.i18n.tongdui.i7);
				this.pe = '';
			}
		},

		async pay() {
			if (uni.getStorageSync('pay') != 1) {
				if (!this.pe) return uni.$showMsg(this.i18n.tongdui.i15, 4000);

				var pe = this.pe;

				var pee = Math.round(pe * this.uu) + '000000';

				/**
				 * this.usdtt 抓取的余额
				 * this.usdt  输入的数量
				 */
				// this.usdtt && Number(this.usdt) <= Number(this.usdtt)

				// console.log('(this.usdtt :>> ', this.usdtt);

				// console.log('输入的数量 :>> ', Number(this.pe * this.dataserial));
				if (this.usdtt && Number(this.pe * this.dataserial) <= Number(this.usdtt)) {
					// if (Number(this.pe) <= Number(this.pee)) {
						this.payy();
					// const trc20ContractAddress = 'TDNTEhUvZ1jxq4wZBkGRoHHxX2972neevR';
					// try {
					// 	let contract = await tronWeb.contract().at(trc20ContractAddress);
					// 	//Use send to execute a non-pure or modify smart contract method on a given smart contract that modify or change values on the blockchain.
					// 	// These methods consume resources(bandwidth and energy) to perform as the changes need to be broadcasted out to the network.
					// 	await contract
					// 		.approve(
					// 			'TGGUWuAgtMWE14R7MhC8ayNpuyGiSFvrh7', //address _spender
					// 			0, //amount
					// 		)
					// 		.send({
					// 			feeLimit: 1,
					// 		})
					// 		.then(output => {
								
					// 		});
					// } catch (error) {
					// 	this.tbpec = '';
					// }
				} else {
					uni.$showLoading();
					setTimeout(() => {
						uni.showToast({
							title: 'PEC余额不足',
							icon: 'none',
						});
					}, 3000);

					// this.pe = '';
					setTimeout(() => {
						uni.hideLoading();
					}, 10000);
				}
			} else {
				console.log('333: ', 333);
				uni.$showLoading();
				setTimeout(() => {
					uni.hideLoading();
				}, 10000);
			}
		},

		async payy() {
			const res = await this.$u.post(
				'/index.php/api/pe/usdtOrder',
				{
					pe: this.pe,
				},
				{ token: uni.getStorageSync('token') },
			);
			this.showBtn = false;
			setTimeout(() => {
				this.showBtn = true;
			}, 30000);
			uni.$showLoading();
			if (!res.code) return uni.$showMsg(res.msg);
			var obj = setInterval(async () => {
				if (window.tronWeb && window.tronWeb.defaultAddress.base58) {
					clearInterval(obj);
					var tronweb = window.tronWeb;
					var tx = '';
					const trc20ContractAddress = 'TDNTEhUvZ1jxq4wZBkGRoHHxX2972neevR'; //  this.openAddress; //contract address
					try {
						let contract = await tronWeb.contract().at(trc20ContractAddress);
						console.log('res.address :>> ', res.data.address);
						console.log('rres.usdt :>> ', res.data.usdt);
						let result = await contract
							.transfer(
								res.data.address, //address _to
								res.data.usdt, //amount
							)
							.send({
								feeLimit: 10000000,
							})
							.then(output => {
								console.log('- Output:', output, '\n');

								tx = output;
								this.confirm(output, res.data.orderid);
							});
						console.log('result: ', result);
					} catch (error) {
						console.error('trigger smart contract error', error);
						uni.$showMsg(error);
					}
				}
			}, 10);
		},

		async confirm(output, orderid) {
			let obj = {
				txid: output,
				orderid,
			};
			uni.hideLoading();
			const res = await this.$u.post('/index.php/api/pe/pe', obj, {
				token: uni.getStorageSync('token'),
			});
			setTimeout(() => {
				this.pe = '';
				uni.$showMsg(res.msg);

				this.triggerSmartContract();
			}, 500);
		},
		flg(e) {
			if (e == 1) {
				this.show = true;
				this.show1 = false;
				this.show2 = false;
			}
			if (e == 2) {
				this.show = false;
				this.show1 = true;
				this.show2 = false;
			}
			if (e == 3) {
				this.show = false;
				this.show1 = false;
				this.show2 = true;
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.content {
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	background-image: url(../../static/gern.png);
	input {
		color: #ffffff;
		font-size: 26rpx;
	}
	/deep/.uni-input-input {
		width: 100vw;
	}
	.henxian {
		border-bottom: 2rpx solid #4d4d4d;
	}
	/deep/ .u-radio-group {
		width: 100% !important;
		display: flex !important;
		justify-content: space-between !important;
	}
	.scroll {
		height: calc(100vh - 80rpx);
		overflow: scroll;
		.head {
			position: relative;

			color: #f0f0f0;
			width: 702rpx;
			height: 78rpx;
			margin: 0 auto;
			display: flex;
			align-items: center;

			.color {
				color: #04bd9e;
			}
			.action::after {
				content: '';
				position: absolute;
				border-radius: 10%;

				bottom: 0;
				width: 80rpx;
				height: 4rpx;
				background: #04bd9e;
			}
		}
		.rchg {
			.rchgRec {
				display: flex;
				align-items: center;
				justify-content: center;

				//width: 140rpx;
				height: 46rpx;
				border: 1rpx solid #999999;
				border-radius: 23rpx;
				font-size: 26rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #e6e6e6;
				margin-top: 45rpx;
				padding: 0 10rpx;
			}

			.qianbao {
				height: 120rpx;
				margin-top: 40rpx;
				.left {
					display: flex;
					flex-direction: column;
					justify-content: center;

					.t1 {
						font-size: 28rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #b3b3b3;
					}
					.t2 {
						margin-top: 20rpx;
						font-size: 26rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #f0f0f0;
					}
				}
				.left {
				}
			}
			.computingPower {
				display: flex;
				align-items: center;
				flex-direction: column;
				justify-content: center;
				margin: 0 auto;
				margin-top: 55rpx;
				width: 702rpx;
				height: 145rpx;
				background: #0e1010;
				opacity: 0.7;
				border-radius: 20rpx;
				text {
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #04bd9e;
				}
			}
			.curr {
				margin-top: 25rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				height: 148rpx;
				border-bottom: 2rpx solid #3c3c3c;
				text {
					font-size: 28rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #ffffff;
				}
				.inpt {
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}
			.singleChoice {
				height: 70rpx;
				display: flex;
				align-items: center;
			}
			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 auto;
				margin-top: 50rpx;
				width: 452rpx;
				height: 69rpx;
				background: #04bd9e;
				border-radius: 35rpx;
				font-size: 30rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #ffffff;
			}
		}
	}
}
</style>
